<template>
  <div v-if="visible" class="floating-panel">
    <span class="close-btn" role="button" aria-label="关闭" tabindex="0" @click="handleCancel" @keydown.enter="handleCancel">×</span>
    <div class="floating-panel__header">属性分配</div>
    <div class="floating-panel__body">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="90px" size="small" class="zone-sect-form">
        <el-form-item label="集合" prop="setKey">
          <el-select v-model="form.setKey" placeholder="请选择集合" filterable clearable style="width: 240px">
            <el-option v-for="g in availableSets" :key="g.key" :label="g.name" :value="g.key" />
          </el-select>
        </el-form-item>
        <el-form-item label="截面属性" prop="sectionKey">
          <el-select v-model="form.sectionKey" placeholder="请选择截面属性" filterable clearable style="width: 240px">
            <el-option v-for="s in availableSections" :key="s.key" :label="s.name" :value="s.key" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :disabled="!form.sectionKey" @click="handleConfirm">确认</el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
      <div v-if="availableSections.length === 0" class="empty-hint">暂无可选截面</div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted, onBeforeUnmount, computed, watch } from 'vue'
import type { ProjectTreeNode } from '@/store/modules/tree'
import { useTreeStore } from '@/store/modules/tree'
import { usePropertyForm } from '../composables/usePropertyForm'
import { useAvailableSets } from '../composables/useAvailableSets'
import { useFindNodesByParentTypeAndType } from '../composables/findNodesByParentTypeAndType'

const props = defineProps<{ node?: ProjectTreeNode | null; projectId?: number | string | null }>()
const emit = defineEmits<{ (e:'cancel'):void; (e:'confirm'):void; (e:'update', v:any):void }>()

const visible = ref(true)
function handleCancel(){ visible.value=false; emit('cancel') }
function handleKey(e:KeyboardEvent){ if(e.key==='Escape'&&visible.value){ handleCancel() } }

// 单字段 form (原 sectionKey 改为 key)
const form = reactive<{ sectionKey: string; setKey: string }>({ sectionKey: '', setKey: '' })
const rules = {
  sectionKey: [{ required: true, message: '请选择截面属性', trigger: 'change' }],
  setKey: [{ required: true, message: '请选择集合', trigger: 'change' }]
}

const treeStore = useTreeStore()
// 直接获取所有截面子节点 sectionChildren
const { availableSets: sectionChildren } = useAvailableSets(computed(()=>props.projectId), 'sectionChildren')
const availableSections = computed(() => sectionChildren.value.map(s => ({ key: s.key, name: s.name })) )
// 收集所有集合：找到 type==='set' 节点的 children 中 type==='setChildren'
const { result: setChildren } = useFindNodesByParentTypeAndType(
  computed(() => props.projectId),
  'partChildren',
  'setChildren',
  props.node?.key || ''
)
const availableSets = computed(() => setChildren.value.map(s => ({ key: s.key, name: s.name })) )
function ensureLoaded(){ if (props.projectId != null && treeStore.getTree(props.projectId).length === 0) treeStore.load(props.projectId) }

// 适配 emit：usePropertyForm 只发 confirm/cancel，这里扩展 update
const bridgeEmit = (e:'confirm'|'cancel') => { if(e==='confirm'){ emit('update', { ...form }); emit('confirm') } else emit('cancel') }
const { formRef, handleConfirm } = usePropertyForm(form, { node: props.node, projectId: props.projectId, persist: false, namespace: 'zoneSect' }, bridgeEmit)

// 移除兼容旧数据逻辑：不再进行名称->key 转换

onMounted(()=>{ window.addEventListener('keydown',handleKey); ensureLoaded() })
onBeforeUnmount(()=>window.removeEventListener('keydown',handleKey))
watch(() => props.projectId, () => ensureLoaded())
</script>
<style scoped lang="scss">
@use './common.scss' as *;
.zone-sect-form { display:flex; flex-direction:column; gap:8px; }
.empty-hint { color:#999; font-size:12px; margin-top:4px; }
</style>